<!--
 * @Author: dumin 173672326@qq.com
 * @Date: 2025-03-13 16:51:15
 * @LastEditors: dumin 173672326@qq.com
 * @LastEditTime: 2025-03-13 16:56:33
 * @Description: 导入模板按钮
-->
<template>
  <el-button v-bind="attrs" type="primary" plain @click="onDownload">
    <slot>导入模板</slot>
  </el-button>
</template>

<script setup>
import config from '@/config'
import { ElMessage } from 'element-plus'

const props = defineProps({
  // 下载线上文件时使用 url 地址
  url: String,

  // 是否使用 public 下的文件
  localPath: {
    type: Boolean,
    default: true,
  },

  // 下载的文件名称，带后缀
  fileName: String,

  // el-button 的属性
  attrs: {
    type: Object,
    default: () => ({}),
  },
})

function onDownload() {
  const downloadUrl = props.localPath ? `${config.base}/template/${props.fileName}` : props.url
  if (!downloadUrl) return
  fetch(downloadUrl, {
    method: 'GET',
  })
    .then(response => {
      return response.blob()
    })
    .then(blob => {
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = props.fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      ElMessage.success('操作成功')
    })
}
</script>
